/**
 * 
 */
package uniandes.dermatologia.tasks;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import uniandes.dermatologia.TestListActivity;
import uniandes.dermatologia.singleton.DermatologiaUniandesApp;
import uniandes.dermatologia.training.pojos.Container;
import uniandes.dermatologia.training.pojos.Test;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * @author Julio
 *
 */
public class TestsTask extends AsyncTask<String, Void, Object> {
	
	private static final String URL = "http://157.253.236.91:3000/mytests_services.json";
	
	private static final String TOKEN = "token";
	
	private DermatologiaUniandesApp app;
	
	private Context context;
	
	
	public TestsTask(DermatologiaUniandesApp app, Context context)
	{		
		this.app = app;
		this.context = context;
	}

	/*
	 * (non-Javadoc)
	 * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
	 */
	@Override
	protected Object doInBackground(String... params) {
		String json = "";
        try {
            HttpPost httppost = null;                     	
            httppost = requestTests(params[0]);
            HttpClient httpclient = new DefaultHttpClient();
            Log.d("request", httppost.getURI().toString());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();
            String UTF8 = "utf8";
            int BUFFER_SIZE = 8192;
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, UTF8), BUFFER_SIZE);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
            json = sb.toString();
            Log.d("Skinhealth Server response",json);
        } catch (Exception e) {
            Log.e("Skinhealth Died", e.getMessage());
            e.printStackTrace();
        }
        return json;
	}
	
	private HttpPost requestTests(String token) throws UnsupportedEncodingException
	{
        HttpPost httppost = new HttpPost(URL);                
        ArrayList<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(1);
        BasicNameValuePair nameValuePair = new BasicNameValuePair(TOKEN, token);
        nameValuePairs.add(nameValuePair);
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
        httppost.setEntity(entity);
		return httppost; 
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	
	@Override
	protected void onPostExecute(Object result) {		
		super.onPostExecute(result);
		try {
			String json = (String)result;
			
			json = "{tests:"+json+"}";
			Gson gson = new GsonBuilder().setDateFormat(DermatologiaUniandesApp.DATE_PATTERN).create();
			Container container = gson.fromJson(json, Container.class);
			ArrayList<Test> tests = container.getTests();
			if( tests != null)
			{
				app.setTests(tests);
				Intent intent = new Intent(context, TestListActivity.class);
				context.startActivity(intent);
			}			
		} catch (Exception e) {
			Log.e("Get test Error", "Error: " + e.getMessage());
		}
		
	}
	

}
